package com.anxin.registerManagement.service;

import cn.hutool.core.util.ObjectUtil;
import com.anxin.registerManagement.bean.persist.PhotoResource;
import com.anxin.registerManagement.bean.persist.User;
import com.anxin.registerManagement.exception.AuthException;
import com.anxin.registerManagement.exception.BusinessException;
import com.anxin.registerManagement.mapper.PhotoResourceMapper;
import com.anxin.registerManagement.mapper.UserMapper;
import com.anxin.registerManagement.util.Const;
import com.anxin.registerManagement.util.jwt.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;

/**
 * @author 叶前呈
 * @date 2022/3/26 20:16
 */
@Service
public class FileService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PhotoResourceMapper photoResourceMapper;

    @Transactional(rollbackFor = Exception.class)
    public void uploadImage(MultipartFile multipartFile, String jwt) throws IOException {
        if (!JwtUtil.check(jwt)) {
            throw new BusinessException(Const.JWT_ERROR);
        }
        // 获取jwt中的id
//        String userId = JwtUtil.getClaim(jwt, "id");
        // TODO:这里先设置成1
        String userId = "1";
        if (ObjectUtil.isEmpty(userId)) {
            throw new AuthException(Const.ERROR_JWT_TOKEN);
        }
        // 设置照片内容
        String photoContent = Base64.getEncoder().encodeToString(multipartFile.getBytes());
        // 查询用户，通过用户的照片id判断照片是否存在
        User queryUser = userMapper.selectById(userId);
        LambdaQueryWrapper<PhotoResource> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PhotoResource::getId, queryUser.getPhotoId());
        PhotoResource photoResource = photoResourceMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtil.isEmpty(photoResource)) {
            // 空则增加
            PhotoResource insertPhoto = new PhotoResource();
            insertPhoto.setId(Integer.parseInt(userId));
            insertPhoto.setPhotoContent(photoContent);
            photoResourceMapper.insert(insertPhoto);
            // 照片增加后，对用户信息进行修改
            User updateUser = new User();
            updateUser.setId(Integer.parseInt(userId));
            updateUser.setPhotoId(insertPhoto.getId());
            userMapper.updateById(updateUser);
            LOGGER.info("添加照片成功");
        } else {
            // 非空则修改
            photoResource.setPhotoContent(photoContent);
            photoResourceMapper.updateById(photoResource);
            LOGGER.info("修改照片成功");
        }
    }

    /**
     * 获得照片
     */
    public byte[] getPhoto(HttpServletRequest request) {
        // 由于这里全局的过滤器已经校验过，因此不需要校验
        // TODO:这里jwt记得修改
//        String jwt = request.getHeader(Const.jwtName);
//        String userId = JwtUtil.getClaim(jwt, "id");
        String userId = "1";
        PhotoResource photoResource = photoResourceMapper.selectById(userMapper.selectById(userId).getPhotoId());
        if (ObjectUtil.isEmpty(photoResource)) {
            return null;
        }
        byte[] photoContent = Base64.getDecoder().decode(photoResource.getPhotoContent());
        return photoContent;

    }

}
